import React, { createContext, ReactElement } from 'react';

import { State, Action, Context } from './types';
import actions, { getData } from './actions';
import Provider from '../../../../components/Provider';
import { GRADE_LIST } from './constant';
import { isIOS } from '../../../../constant';

export const initialState: State = {
  data: {
    banners: [],
    demoCommodities: [],
    systemCommodities: []
  },
  isShowSelectGrade: false,
  isFetchFailed: false,
  currentGrade: isIOS ? GRADE_LIST[2] : GRADE_LIST[0]
};

export const reducer = (state: State, action: Action): State => {
  switch (action.type) {
    case 'SET_DATA': {
      return {
        ...state,
        data: action.value,
        isFetchFailed: false
      };
    }
    case 'SET_IS_SHOW_SELECT_GRADE':
      return { ...state, isShowSelectGrade: action.value };
    case 'SET_CURRENT_GRADE':
      return { ...state, currentGrade: action.value };
    case 'FETCH_FAILED':
      return { ...state, isFetchFailed: true };
    default:
      return state;
  }
};

export const Store = createContext<Context>({
  state: initialState
});

export default (props: { [key: string]: any }): ReactElement => {
  return (
    <Provider
      reducer={reducer}
      initialState={initialState}
      Store={Store}
      actions={actions}
      reload={getData}
      {...props}
    />
  );
};
